class Solution(object):
def lengthOfLongestSubstring\(self, s\):
"""
:type s: str
:rtype: int
"""
lst={}
i=0
maxlen=0
nonrepet=True
while \(i<len\(s\)\):
if s\[i\] not in lst:
lst\[s\[i\]\]=\[i\]
else:
lst\[s\[i\]\]+=\[i\]
nonrepet=False
i+=1
print\(lst\)
if nonrepet:
return len\(s\)
else:
for i in lst:
places=len\(lst\[i\]\)
curmax=0
for j in range\(0,places-1\):
if \(lst\[i\]\[j+1\]-lst\[i\]\[j\]\)>curmax:
curmax=lst\[i\]\[j+1\]-lst\[i\]\[j\]
if curmax>maxlen:
maxlen=curmax
return maxlen
这是我最开始的想法。我的思路是找到最长的一对重复字母之间的长度。但是这种是处理不了'pww'这种例子的。我给的结果是1,但是答案是2
然后网上找了一个答案:
class Solution(object):
def lengthOfLongestSubstring\(self, s\):
"""
:type s: str
:rtype: int
"""
ans, start, end = 0, 0, 0
countDict = {}
for c in s:
end += 1
countDict\[c\] = countDict.get\(c, 0\) + 1
while countDict\[c\] > 1:
\#print\(c,s\[start\],countDict\[s\[start\]\],start\)
countDict\[s\[start\]\] -= 1
start += 1
ans = max\(ans, end - start\)
return ans
woc牛逼。这个算法O(n)。思路是这样的。先假定从0开始。对于每次看到的新的字符,如果以前看到过,那么就加入dictionary,并设为1,反之就进判断。
因为他是根据start和end来判断的。如果当前这个元素有重复,那么dictionary中对应的开始元素就要后移一个,同时start标志位也要往后移。知道当前元素没有重复位置。
然后这个是相当于开头和结尾同时移动来判断的。
我觉得还是很牛逼的。